package com.liu.model;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class IO {
	public static String DatatoJson(List<Group> gLst, List<Ac> aLst) {
		try {
			JSONObject obj = new JSONObject();

			JSONArray ja1 = new JSONArray();
			for (int i = 0; i < gLst.size(); i++) {
				ja1.put(gLst.get(i).toJsonObj());
			}
			obj.put("gLst", ja1);
			JSONArray ja2 = new JSONArray();
			for (int i = 0; i < aLst.size(); i++) {
				ja2.put(aLst.get(i).toJsonObj());
			}
			obj.put("aLst", ja2);
			return obj.toString();
		} catch (Exception e) {
			return null;
		}
	}

	public static void JsonToData(String json, List<Group> gLst, List<Ac> aLst) {
		try {
			JSONObject obj = new JSONObject(json);
			JSONArray ja1 = obj.getJSONArray("gLst");
			for (int i = 0; i < ja1.length(); i++) {
				gLst.add(Group.JsonToGroup(ja1.getJSONObject(i)));
			}
			JSONArray ja2 = obj.getJSONArray("aLst");
			for (int i = 0; i < ja2.length(); i++) {
				aLst.add(Ac.JsonToAc(ja2.getJSONObject(i)));
			}
		} catch (JSONException e) {
		}
	}

	public static boolean StrToFile(String str, String filePath) {
		try {
			FileOutputStream FOS = new FileOutputStream(filePath);
			byte[] s1 = str.getBytes();
			byte[] s2 = new byte[s1.length];
			for (int i = 0; i < s1.length; i++) {
				s2[i] = s1[s1.length - i - 1];
			}
			FOS.write(s2);
			FOS.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static String FileToStr(String filePath) {
		try {
			FileInputStream FIS = new FileInputStream(filePath);
			List<Byte> data = new ArrayList<Byte>();
			byte b = (byte) FIS.read();
			while (b != -1) {
				data.add(b);
				b = (byte) FIS.read();
			}
			byte[] bb = new byte[data.size()];
			for (int i = 0; i < bb.length; i++) {
				bb[i] = data.get(bb.length - i - 1);
			}
			FIS.close();
			return new String(bb);
		} catch (Exception e) {
			return null;
		}
	}
}
